package com.hrma.config;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.hrma.entity.exception.MustHasException;
import com.hrma.entity.exception.NotPermissionException;
import com.hrma.entity.exception.UserNameOrPasswordException;
import com.hrma.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;
import java.util.List;

/**
 * create by 2023/1/9.
 *
 * @author udbjqr
 */
@RestControllerAdvice("com.hrma.control")
@Slf4j
public class ControlAdvice {
	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler({JWTVerificationException.class, JWTDecodeException.class})
	public Result<?> handleTokenError(JWTVerificationException e) {
		return Result.err(Result.NOT_LOGIN, e.getMessage(), null);
	}

	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(MustHasException.class)
	public Result<?> mustHas(MustHasException e) {
		return Result.err(Result.MUST_HAS, e.getMessage(), null);
	}

	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(NotPermissionException.class)
	public Result<?> notPermission(NotPermissionException e) {
		return Result.err(Result.NOT_POWER, e.getMessage(), null);
	}

	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(UserNameOrPasswordException.class)
	public Result<?> loginErr(UserNameOrPasswordException e) {
		return Result.err(Result.USER_OR_PASSWD, e.getMessage(), null);
	}

	@ResponseStatus(HttpStatus.OK)
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Result<?> handleArgValid(MethodArgumentNotValidException e) {
		List<String> result = new ArrayList<>(e.getErrorCount());
		for (ObjectError err : e.getBindingResult().getAllErrors()) {
			String value = "类:" + err.getObjectName();
			if (err instanceof FieldError){
				value += "，出错字段:"+((FieldError) err).getField();
			}
			value += "，失败消息:" + err.getDefaultMessage();

			result.add(value);
		}

		return Result.err(Result.PARA_VALID_ERROR, "校验失败", result);
	}

}

